package icu.study.common.security.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
        for (ConfigAttribute configAttribute : configAttributes) {
            //ll如果你请求的urL在数据库中不具备角色
            if ("ROLE_DEFAULT".equals(configAttribute.getAttribute())) {
                //再判断是不是匿名用户（也就是未登录)
                if (authentication instanceof AnonymousAuthenticationToken) {
                    System.out.println(">>>>>>>>>>>>>>>>>匿名用户>>>>>>>>>>>>>>>>>>");
                    throw new AccessDeniedException("权限不足，无法访问!");
                } else {
                    //这里面就是已经登陆的其他类型用户（意思就是什么用户都可以访问）直接放行
                    System.out.println(">>>>>>>>>>>>其他类型用户>>>>>>>>>>>>>>>>>>>>>");
                    return;
                }
            }
            //如果你访问的路径在数据库中具有角色就会来到这里
            //Authentication这里面存放着登陆后的用户所有信息
            for (GrantedAuthority authority : auths) {
                System.out.println(">>>>>>>>>>>>>>>>>>authority(账户所拥有的权限):" + authority.getAuthority());
                System.out.println(">>>>>>>>>>>>>>>configAttribute（路径需要的角色):" + configAttribute.getAttribute());
                if (authority.getAuthority().equals(configAttribute.getAttribute())) {
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>进来>>>>>>>>>>>>>>>>>>>>>>");
                    return;
                }
                //路径需要的角色和账户所拥有的角色作比较
            }
            throw new AccessDeniedException("权限不足，无法访问!");
        }
    }


    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
